package com.hmdp.service.impl;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.ScrollResult;
import com.hmdp.entity.Follow;
import com.hmdp.service.IFollowService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;

import cn.hutool.core.bean.BeanUtil;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query().orderByDesc("liked").page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(item -> {
            this.queryBlogUser(item);
            this.isBlogLiked(item);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = this.getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        queryBlogUser(blog);
        // 判断用户是否已经点过赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        // 判断当前用户是否已经点赞
        Long userId = UserHolder.getUser().getId();
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, userId.toString());
        // 判断用户是否已经点赞
        if (score == null) {
            // 用户没有点赞，更新数据库点赞数
            boolean isSuccess = this.lambdaUpdate().setSql("liked = liked + 1").eq(Blog::getId, id).update();
            if (isSuccess) {
                // 数据库更新成功，将用户id写入Redis
                stringRedisTemplate.opsForZSet().add(BLOG_LIKED_KEY + id, userId.toString(),
                    System.currentTimeMillis());
            }
        } else {
            // 用户已经点赞，则取消点赞，数据库点赞减1
            boolean isSuccess = this.lambdaUpdate().setSql("liked = liked - 1").eq(Blog::getId, id).update();
            if (isSuccess) {
                // 数据库更新成功，将用户id从Redis中删除
                stringRedisTemplate.opsForZSet().remove(BLOG_LIKED_KEY + id, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(BLOG_LIKED_KEY + id, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        List<UserDTO> userDTOS = userService.query().in("id", ids).last("order by field(id," + idStr + ")").list()
            .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        boolean isSuccess = this.save(blog);
        if (!isSuccess) {
            return Result.fail("新增笔记失败!");
        }
        // 获取该用户的粉丝
        List<Follow> follows = followService.lambdaQuery().eq(Follow::getFollowUserId, user.getId()).list();
        follows.forEach(follow -> {
            Long userId = follow.getUserId();
            stringRedisTemplate.opsForZSet().add(FEED_KEY + userId, blog.getId().toString(),
                System.currentTimeMillis());
        });
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 获取当前用户id
        Long userId = UserHolder.getUser().getId();
        // 查询收件箱
        Set<ZSetOperations.TypedTuple<String>> typedTuples =
            stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(FEED_KEY + userId, 0, max, offset, 2);
        // 分控判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }

        ArrayList<Long> ids = new ArrayList<>(typedTuples.size());
        AtomicLong minTime = new AtomicLong();
        AtomicInteger os = new AtomicInteger(1);
        typedTuples.forEach(tuple -> {
            // 获取id
            ids.add(Long.valueOf(Objects.requireNonNull(tuple.getValue())));
            // 获取分数（时间戳）
            long time = Objects.requireNonNull(tuple.getScore()).longValue();
            if (time == minTime.get()) {
                os.getAndIncrement();
            } else {
                minTime.set(time);
                os.set(1);
            }
        });

        // 将id转为字符串
        String idStr = StrUtil.join(",", ids);

        List<Blog> blogs = this.query().in("id", ids).last("order by field(id," + idStr + ")").list();
        blogs.forEach(blog -> {
            queryBlogUser(blog);
            // 判断用户是否已经点过赞
            isBlogLiked(blog);
        });

        // 封装结果对象
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime.get());
        scrollResult.setOffset(os.get());
        return Result.ok(scrollResult);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，不查询点赞状态
            return;
        }
        Long userId = user.getId();
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + blog.getId(), userId.toString());
        blog.setIsLike(score != null);
    }
}
